
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编写你的第一个 Django 应用，第 4 部分 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="编写你的第一个 Django 应用，第 5 部分" href="tutorial05.html" />
    <link rel="prev" title="编写你的第一个 Django 应用，第 3 部分" href="tutorial03.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="tutorial03.html" title="编写你的第一个 Django 应用，第 3 部分">previous</a>
     |
    <a href="index.html" title="开始" accesskey="U">up</a>
   |
    <a href="tutorial05.html" title="编写你的第一个 Django 应用，第 5 部分">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="intro-tutorial04">
            
  <div class="section" id="s-writing-your-first-django-app-part-4">
<span id="writing-your-first-django-app-part-4"></span><h1>编写你的第一个 Django 应用，第 4 部分<a class="headerlink" href="#writing-your-first-django-app-part-4" title="永久链接至标题">¶</a></h1>
<p>这一篇从 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a>  结尾的地方继续讲起。我们将继续编写投票应用，专注于表单处理并且精简我们的代码。</p>
<div class="admonition-where-to-get-help admonition">
<p class="first admonition-title">从哪里获得帮助：</p>
<p class="last">如果你在阅读本教程的过程中有任何疑问，可以前往 FAQ 的 <a class="reference internal" href="../faq/help.html"><span class="doc">获取帮助</span></a> 的版块。</p>
</div>
<div class="section" id="s-write-a-minimal-form">
<span id="write-a-minimal-form"></span><h2>编写一个简单的表单<a class="headerlink" href="#write-a-minimal-form" title="永久链接至标题">¶</a></h2>
<p>让我们更新一下在上一个教程中编写的投票详细页面的模板  (&quot;polls/detail.html&quot;) ，让它包含一个 HTML <code class="docutils literal notranslate"><span class="pre">&lt;form&gt;</span></code> 元素：</p>
<div class="literal-block-wrapper docutils container" id="id1">
<div class="code-block-caption"><span class="caption-text">polls/templates/polls/detail.html</span><a class="headerlink" href="#id1" title="永久链接至代码">¶</a></div>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;polls:vote&#39;</span> <span class="nv">question.id</span> <span class="cp">%}</span><span class="s">&quot;</span> <span class="na">method</span><span class="o">=</span><span class="s">&quot;post&quot;</span><span class="p">&gt;</span>
<span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span>
<span class="p">&lt;</span><span class="nt">fieldset</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">legend</span><span class="p">&gt;&lt;</span><span class="nt">h1</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;&lt;/</span><span class="nt">legend</span><span class="p">&gt;</span>
    <span class="cp">{%</span> <span class="k">if</span> <span class="nv">error_message</span> <span class="cp">%}</span><span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;&lt;</span><span class="nt">strong</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">error_message</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">strong</span><span class="p">&gt;&lt;/</span><span class="nt">p</span><span class="p">&gt;</span><span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span>
    <span class="cp">{%</span> <span class="k">for</span> <span class="nv">choice</span> <span class="k">in</span> <span class="nv">question.choice_set.all</span> <span class="cp">%}</span>
        <span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;radio&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;choice&quot;</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;choice</span><span class="cp">{{</span> <span class="nb">forloop</span><span class="nv">.counter</span> <span class="cp">}}</span><span class="s">&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{{</span> <span class="nv">choice.id</span> <span class="cp">}}</span><span class="s">&quot;</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="nt">label</span> <span class="na">for</span><span class="o">=</span><span class="s">&quot;choice</span><span class="cp">{{</span> <span class="nb">forloop</span><span class="nv">.counter</span> <span class="cp">}}</span><span class="s">&quot;</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">choice.choice_text</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">label</span><span class="p">&gt;&lt;</span><span class="nt">br</span><span class="p">&gt;</span>
    <span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="p">&lt;/</span><span class="nt">fieldset</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;submit&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;Vote&quot;</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="nt">form</span><span class="p">&gt;</span>
</pre></div>
</div>
</div>
<p>简要说明：</p>
<ul class="simple">
<li>上面的模板在 Question 的每个 Choice 前添加一个单选按钮。 每个单选按钮的 <code class="docutils literal notranslate"><span class="pre">value</span></code> 属性是对应的各个 Choice 的 ID。每个单选按钮的 <code class="docutils literal notranslate"><span class="pre">name</span></code> 是 <code class="docutils literal notranslate"><span class="pre">&quot;choice&quot;</span></code> 。这意味着，当有人选择一个单选按钮并提交表单提交时，它将发送一个 POST 数据 <code class="docutils literal notranslate"><span class="pre">choice=#</span></code> ，其中# 为选择的 Choice 的 ID。这是 HTML 表单的基本概念。</li>
<li>我们设置表单的 <code class="docutils literal notranslate"><span class="pre">action</span></code> 为 <code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">url</span> <span class="pre">'polls:vote'</span> <span class="pre">question.id</span> <span class="pre">%}</span></code> ，并设置  <code class="docutils literal notranslate"><span class="pre">method=&quot;post&quot;</span></code> 。使用 <code class="docutils literal notranslate"><span class="pre">method=&quot;post&quot;</span></code> （与其相对的是 <code class="docutils literal notranslate"><span class="pre">method=&quot;get&quot;`）是非常重要的，因为这个提交表单的行为会改变服务器端的数据。</span> <span class="pre">无论何时，当你需要创建一个改变服务器端数据的表单时，请使用</span> <span class="pre">``method=&quot;post&quot;</span></code> 。这不是 Django 的特定技巧；这是优秀的网站开发技巧。</li>
<li><code class="docutils literal notranslate"><span class="pre">forloop.counter</span></code> 指示 <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-for"><code class="xref std std-ttag docutils literal notranslate"><span class="pre">for</span></code></a> 标签已经循环多少次。</li>
<li>由于我们创建一个 POST 表单（它具有修改数据的作用），所以我们需要小心跨站点请求伪造。 谢天谢地，你不必太过担心，因为 Django 自带了一个非常有用的防御系统。 简而言之，所有针对内部 URL 的 POST 表单都应该使用  <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-csrf_token"><code class="xref std std-ttag docutils literal notranslate"><span class="pre">{%</span> <span class="pre">csrf_token</span> <span class="pre">%}</span></code></a> 模板标签。</li>
</ul>
<p>现在，让我们来创建一个 Django 视图来处理提交的数据。记住，在 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中，我们为投票应用创建了一个 URLconf ，包含这一行：</p>
<div class="literal-block-wrapper docutils container" id="id2">
<div class="code-block-caption"><span class="caption-text">polls/urls.py</span><a class="headerlink" href="#id2" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">path</span><span class="p">(</span><span class="s1">&#39;&lt;int:question_id&gt;/vote/&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
</pre></div>
</div>
</div>
<p>我们还创建了一个 <code class="docutils literal notranslate"><span class="pre">vote()</span></code> 函数的虚拟实现。让我们来创建一个真实的版本。 将下面的代码添加到 <code class="docutils literal notranslate"><span class="pre">polls/views.py</span></code> ：</p>
<div class="literal-block-wrapper docutils container" id="id3">
<div class="code-block-caption"><span class="caption-text">polls/views.py</span><a class="headerlink" href="#id3" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span><span class="p">,</span> <span class="n">HttpResponseRedirect</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>

<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span><span class="p">,</span> <span class="n">Question</span>
<span class="c1"># ...</span>
<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">selected_choice</span> <span class="o">=</span> <span class="n">question</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;choice&#39;</span><span class="p">])</span>
    <span class="k">except</span> <span class="p">(</span><span class="ne">KeyError</span><span class="p">,</span> <span class="n">Choice</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">):</span>
        <span class="c1"># Redisplay the question voting form.</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span>
            <span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">,</span>
            <span class="s1">&#39;error_message&#39;</span><span class="p">:</span> <span class="s2">&quot;You didn&#39;t select a choice.&quot;</span><span class="p">,</span>
        <span class="p">})</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">votes</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
        <span class="c1"># Always return an HttpResponseRedirect after successfully dealing</span>
        <span class="c1"># with POST data. This prevents data from being posted twice if a</span>
        <span class="c1"># user hits the Back button.</span>
        <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;polls:results&#39;</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">question</span><span class="o">.</span><span class="n">id</span><span class="p">,)))</span>
</pre></div>
</div>
</div>
<p>以上代码中有些内容还未在本教程中提到过：</p>
<ul>
<li><p class="first"><a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest.POST" title="django.http.HttpRequest.POST"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.POST</span></code></a>  是一个类字典对象，让你可以通过关键字的名字获取提交的数据。 这个例子中， <code class="docutils literal notranslate"><span class="pre">request.POST['choice']</span></code> 以字符串形式返回选择的 Choice 的 ID。 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest.POST" title="django.http.HttpRequest.POST"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.POST</span></code></a>  的值永远是字符串。</p>
<p>注意，Django 还以同样的方式提供 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest.GET" title="django.http.HttpRequest.GET"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.GET</span></code></a>  用于访问 GET 数据 —— 但我们在代码中显式地使用 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest.POST" title="django.http.HttpRequest.POST"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.POST</span></code></a>  ，以保证数据只能通过 POST 调用改动。</p>
</li>
<li><p class="first">如果在 <code class="docutils literal notranslate"><span class="pre">request.POST['choice']</span></code>  数据中没有提供 <code class="docutils literal notranslate"><span class="pre">choice</span></code> ， POST 将引发一个 <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#KeyError" title="(在 Python v3.10)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> 。上面的代码检查 <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#KeyError" title="(在 Python v3.10)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> ，如果没有给出 <code class="docutils literal notranslate"><span class="pre">choice</span></code> 将重新显示 Question 表单和一个错误信息。</p>
</li>
<li><p class="first">在增加 Choice 的得票数之后，代码返回一个 <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a> 而不是常用的 <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a>  、 <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a>  只接收一个参数：用户将要被重定向的 URL（请继续看下去，我们将会解释如何构造这个例子中的 URL）。</p>
<p>As the Python comment above points out, you should always return an
<a class="reference internal" href="../ref/request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a> after successfully dealing with
POST data. This tip isn't specific to Django; it's good Web development
practice in general.</p>
</li>
<li><p class="first">在这个例子中，我们在 <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a> 的构造函数中使用 <code class="xref py py-func docutils literal notranslate"><span class="pre">reverse()</span></code> 函数。这个函数避免了我们在视图函数中硬编码 URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供的参数。 在本例中，使用在 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中设定的 URLconf， <code class="xref py py-func docutils literal notranslate"><span class="pre">reverse()</span></code> 调用将返回一个这样的字符串：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;/polls/3/results/&#39;</span>
</pre></div>
</div>
<p>其中 <code class="docutils literal notranslate"><span class="pre">3</span></code> 是 <code class="docutils literal notranslate"><span class="pre">question.id</span></code> 的值。重定向的 URL 将调用 <code class="docutils literal notranslate"><span class="pre">'results'</span></code> 视图来显示最终的页面。</p>
</li>
</ul>
<p>正如在 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中提到的，<a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> 是一个 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> 对象。更多关于 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> 对象的内容，请参见 <a class="reference internal" href="../ref/request-response.html"><span class="doc">请求和响应的文档</span></a> 。</p>
<p>当有人对 Question 进行投票后，  <code class="docutils literal notranslate"><span class="pre">vote()</span></code> 视图将请求重定向到 Question 的结果界面。让我们来编写这个视图：</p>
<div class="literal-block-wrapper docutils container" id="id4">
<div class="code-block-caption"><span class="caption-text">polls/views.py</span><a class="headerlink" href="#id4" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>


<span class="k">def</span> <span class="nf">results</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/results.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>
</pre></div>
</div>
</div>
<p>这和 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中的  <code class="docutils literal notranslate"><span class="pre">detail()</span></code> 视图几乎一模一样。唯一的不同是模板的名字。 我们将在稍后解决这个冗余问题。</p>
<p>现在，创建一个 <code class="docutils literal notranslate"><span class="pre">polls/results.html</span></code>  模板：</p>
<div class="literal-block-wrapper docutils container" id="id5">
<div class="code-block-caption"><span class="caption-text">polls/templates/polls/results.html</span><a class="headerlink" href="#id5" title="永久链接至代码">¶</a></div>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>

<span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">choice</span> <span class="k">in</span> <span class="nv">question.choice_set.all</span> <span class="cp">%}</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">choice.choice_text</span> <span class="cp">}}</span> -- <span class="cp">{{</span> <span class="nv">choice.votes</span> <span class="cp">}}</span> vote<span class="cp">{{</span> <span class="nv">choice.votes</span><span class="o">|</span><span class="nf">pluralize</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>

<span class="p">&lt;</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;polls:detail&#39;</span> <span class="nv">question.id</span> <span class="cp">%}</span><span class="s">&quot;</span><span class="p">&gt;</span>Vote again?<span class="p">&lt;/</span><span class="nt">a</span><span class="p">&gt;</span>
</pre></div>
</div>
</div>
<p>现在，在你的浏览器中访问 <code class="docutils literal notranslate"><span class="pre">/polls/1/</span></code> 然后为 Question 投票。你应该看到一个投票结果页面，并且在你每次投票之后都会更新。 如果你提交时没有选择任何 Choice，你应该看到错误信息。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>我们的 <code class="docutils literal notranslate"><span class="pre">vote()</span></code> 视图代码有一个小问题。代码首先从数据库中获取了 <code class="docutils literal notranslate"><span class="pre">selected_choice</span></code> 对象，接着计算 <code class="docutils literal notranslate"><span class="pre">vote</span></code> 的新值，最后把值存回数据库。如果网站有两个方可同时投票在 <em>同一时间</em> ，可能会导致问题。同样的值，42，会被 <code class="docutils literal notranslate"><span class="pre">votes</span></code> 返回。然后，对于两个用户，新值43计算完毕，并被保存，但是期望值是44。</p>
<p class="last">这个问题被称为 <em>竞争条件</em> 。如果你对此有兴趣，你可以阅读 <a class="reference internal" href="../ref/models/expressions.html#avoiding-race-conditions-using-f"><span class="std std-ref">使用 F() 避免竞争条件</span></a> 来学习如何解决这个问题。</p>
</div>
</div>
<div class="section" id="s-use-generic-views-less-code-is-better">
<span id="use-generic-views-less-code-is-better"></span><h2>使用通用视图：代码还是少点好<a class="headerlink" href="#use-generic-views-less-code-is-better" title="永久链接至标题">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">detail()</span></code> （在 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中）和 <code class="docutils literal notranslate"><span class="pre">results()</span></code> 视图都很精简 —— 并且，像上面提到的那样，存在冗余问题。用来显示一个投票列表的 <code class="docutils literal notranslate"><span class="pre">index()</span></code>  视图（也在 <a class="reference internal" href="tutorial03.html"><span class="doc">教程第 3 部分</span></a> 中）和它们类似。</p>
<p>这些视图反映基本的 Web 开发中的一个常见情况：根据 URL 中的参数从数据库中获取数据、载入模板文件然后返回渲染后的模板。 由于这种情况特别常见，Django 提供一种快捷方式，叫做“通用视图”系统。</p>
<p>通用视图将常见的模式抽象化，可以使你在编写应用时甚至不需要编写Python代码。</p>
<p>让我们将我们的投票应用转换成使用通用视图系统，这样我们可以删除许多我们的代码。我们仅仅需要做以下几步来完成转换，我们将：</p>
<ol class="arabic simple">
<li>转换 URLconf。</li>
<li>删除一些旧的、不再需要的视图。</li>
<li>基于 Django 的通用视图引入新的视图。</li>
</ol>
<p>请继续阅读来了解详细信息。</p>
<div class="admonition-why-the-code-shuffle admonition">
<p class="first admonition-title">为什么要重构代码？</p>
<p>一般来说，当编写一个 Django 应用时，你应该先评估一下通用视图是否可以解决你的问题，你应该在一开始使用它，而不是进行到一半时重构代码。本教程目前为止是有意将重点放在以“艰难的方式”编写视图，这是为将重点放在核心概念上。</p>
<p class="last">就像在使用计算器之前你需要掌握基础数学一样。</p>
</div>
<div class="section" id="s-amend-urlconf">
<span id="amend-urlconf"></span><h3>改良 URLconf<a class="headerlink" href="#amend-urlconf" title="永久链接至标题">¶</a></h3>
<p>首先，打开 <code class="docutils literal notranslate"><span class="pre">polls/urls.py</span></code> 这个 URLconf 并将它修改成：</p>
<div class="literal-block-wrapper docutils container" id="id6">
<div class="code-block-caption"><span class="caption-text">polls/urls.py</span><a class="headerlink" href="#id6" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>

<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>

<span class="n">app_name</span> <span class="o">=</span> <span class="s1">&#39;polls&#39;</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">IndexView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&lt;int:pk&gt;/&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">DetailView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&lt;int:pk&gt;/results/&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">ResultsView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;results&#39;</span><span class="p">),</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&lt;int:question_id&gt;/vote/&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
<p>注意，第二个和第三个匹配准则中，路径字符串中匹配模式的名称已经由 <code class="docutils literal notranslate"><span class="pre">&lt;question_id&gt;</span></code> 改为 <code class="docutils literal notranslate"><span class="pre">&lt;pk&gt;</span></code>。</p>
</div>
<div class="section" id="s-amend-views">
<span id="amend-views"></span><h3>改良视图<a class="headerlink" href="#amend-views" title="永久链接至标题">¶</a></h3>
<p>下一步，我们将删除旧的 <code class="docutils literal notranslate"><span class="pre">index</span></code>, <code class="docutils literal notranslate"><span class="pre">detail</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">results</span></code> 视图，并用 Django 的通用视图代替。打开 <code class="docutils literal notranslate"><span class="pre">polls/views.py</span></code> 文件，并将它修改成：</p>
<div class="literal-block-wrapper docutils container" id="id7">
<div class="code-block-caption"><span class="caption-text">polls/views.py</span><a class="headerlink" href="#id7" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">django.views</span> <span class="kn">import</span> <span class="n">generic</span>

<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span><span class="p">,</span> <span class="n">Question</span>


<span class="k">class</span> <span class="nc">IndexView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">ListView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/index.html&#39;</span>
    <span class="n">context_object_name</span> <span class="o">=</span> <span class="s1">&#39;latest_question_list&#39;</span>

    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Return the last five published questions.&quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>


<span class="k">class</span> <span class="nc">DetailView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">DetailView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Question</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/detail.html&#39;</span>


<span class="k">class</span> <span class="nc">ResultsView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">DetailView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Question</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/results.html&#39;</span>


<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="o">...</span> <span class="c1"># same as above, no changes needed.</span>
</pre></div>
</div>
</div>
<p>我们在这里使用两个通用视图： <a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.list.ListView" title="django.views.generic.list.ListView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ListView</span></code></a> 和 <a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.detail.DetailView" title="django.views.generic.detail.DetailView"><code class="xref py py-class docutils literal notranslate"><span class="pre">DetailView</span></code></a> 。这两个视图分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。</p>
<ul class="simple">
<li>每个通用视图需要知道它将作用于哪个模型。 这由 <code class="docutils literal notranslate"><span class="pre">model</span></code> 属性提供。</li>
<li><a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.detail.DetailView" title="django.views.generic.detail.DetailView"><code class="xref py py-class docutils literal notranslate"><span class="pre">DetailView</span></code></a>  期望从 URL 中捕获名为   <code class="docutils literal notranslate"><span class="pre">&quot;pk&quot;</span></code> 的主键值，所以我们为通用视图把 <code class="docutils literal notranslate"><span class="pre">question_id</span></code> 改成 <code class="docutils literal notranslate"><span class="pre">pk</span></code> 。</li>
</ul>
<p>默认情况下，通用视图 <a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.detail.DetailView" title="django.views.generic.detail.DetailView"><code class="xref py py-class docutils literal notranslate"><span class="pre">DetailView</span></code></a> 使用一个叫做 <code class="docutils literal notranslate"><span class="pre">&lt;app</span> <span class="pre">name&gt;/&lt;model</span> <span class="pre">name&gt;_detail.html</span></code> 的模板。在我们的例子中，它将使用 <code class="docutils literal notranslate"><span class="pre">&quot;polls/question_detail.html&quot;</span></code> 模板。<code class="docutils literal notranslate"><span class="pre">template_name</span></code> 属性是用来告诉 Django 使用一个指定的模板名字，而不是自动生成的默认名字。 我们也为 <code class="docutils literal notranslate"><span class="pre">results</span></code> 列表视图指定了 <code class="docutils literal notranslate"><span class="pre">template_name</span></code>  —— 这确保 results 视图和 detail 视图在渲染时具有不同的外观，即使它们在后台都是同一个 <a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.detail.DetailView" title="django.views.generic.detail.DetailView"><code class="xref py py-class docutils literal notranslate"><span class="pre">DetailView</span></code></a> 。</p>
<p>类似地，<a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.list.ListView" title="django.views.generic.list.ListView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ListView</span></code></a> 使用一个叫做  <code class="docutils literal notranslate"><span class="pre">&lt;app</span> <span class="pre">name&gt;/&lt;model</span> <span class="pre">name&gt;_list.html</span></code> 的默认模板；我们使用 <code class="docutils literal notranslate"><span class="pre">template_name</span></code> 来告诉 <a class="reference internal" href="../ref/class-based-views/generic-display.html#django.views.generic.list.ListView" title="django.views.generic.list.ListView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ListView</span></code></a> 使用我们创建的已经存在的 <code class="docutils literal notranslate"><span class="pre">&quot;polls/index.html&quot;</span></code> 模板。</p>
<p>在之前的教程中，提供模板文件时都带有一个包含 <code class="docutils literal notranslate"><span class="pre">question</span></code> 和 <code class="docutils literal notranslate"><span class="pre">latest_question_list</span></code> 变量的 context。对于 <code class="docutils literal notranslate"><span class="pre">DetailView</span></code> ， <code class="docutils literal notranslate"><span class="pre">question</span></code>  变量会自动提供—— 因为我们使用 Django 的模型（Question）， Django 能够为 context 变量决定一个合适的名字。然而对于 ListView， 自动生成的 context 变量是 <code class="docutils literal notranslate"><span class="pre">question_list</span></code>。为了覆盖这个行为，我们提供 <code class="docutils literal notranslate"><span class="pre">context_object_name</span></code> 属性，表示我们想使用 <code class="docutils literal notranslate"><span class="pre">latest_question_list</span></code>。作为一种替换方案，你可以改变你的模板来匹配新的 context 变量 —— 这是一种更便捷的方法，告诉 Django 使用你想使用的变量名。</p>
<p>启动服务器，使用一下基于通用视图的新投票应用。</p>
<p>更多关于通用视图的详细信息，请查看 <a class="reference internal" href="../topics/class-based-views/index.html"><span class="doc">通用视图的文档</span></a></p>
<p>当你对你所写的表单和通用视图感到满意后，请阅读 <a class="reference internal" href="tutorial05.html"><span class="doc">教程的第 5 部分</span></a> 来了解如何测试我们的投票应用。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">编写你的第一个 Django 应用，第 4 部分</a><ul>
<li><a class="reference internal" href="#write-a-minimal-form">编写一个简单的表单</a></li>
<li><a class="reference internal" href="#use-generic-views-less-code-is-better">使用通用视图：代码还是少点好</a><ul>
<li><a class="reference internal" href="#amend-urlconf">改良 URLconf</a></li>
<li><a class="reference internal" href="#amend-views">改良视图</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="tutorial03.html"
                        title="上一章">编写你的第一个 Django 应用，第 3 部分</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="tutorial05.html"
                        title="下一章">编写你的第一个 Django 应用，第 5 部分</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/intro/tutorial04.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="tutorial03.html" title="编写你的第一个 Django 应用，第 3 部分">previous</a>
     |
    <a href="index.html" title="开始" accesskey="U">up</a>
   |
    <a href="tutorial05.html" title="编写你的第一个 Django 应用，第 5 部分">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>